package com.zcxk.dao;

import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.mysqlclient.MySQLPool;
import io.vertx.sqlclient.PoolOptions;
import lombok.Getter;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author wangping
 * @date 2023-07-28 15:53
 */
public class JdbcPool {

  @Getter
  private static MySQLPool pool;

  public static boolean init(Vertx vertx) {
    try {
      // 使用类加载器读取 JSON 配置文件
      InputStream inputStream = JdbcPool.class.getClassLoader().getResourceAsStream("config.json");
      if (inputStream == null) {
        throw new RuntimeException("Config file not found");
      }

      // 读取输入流并转为字符串
      String jsonString = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
      JsonObject config = new JsonObject(jsonString);

      // 从 JSON 对象中提取 JdbcPool 配置
      JsonObject jdbcConfig = config.getJsonObject("JdbcPool");

      MySQLConnectOptions connectOptions = new MySQLConnectOptions()
        .setPort(jdbcConfig.getInteger("port"))
        .setHost(jdbcConfig.getString("host"))
        .setDatabase(jdbcConfig.getString("database"))
        .setUser(jdbcConfig.getString("user"))
        .setPassword(jdbcConfig.getString("password"));

      PoolOptions poolOptions = new PoolOptions()
        .setMaxSize(jdbcConfig.getInteger("maxPoolSize"));

      // 创建客户端池
      pool = MySQLPool.pool(vertx, connectOptions, poolOptions);

      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
}
